package com.wn.login.user

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.tbruyelle.rxpermissions3.RxPermissions
import com.wn.common.constant.USER_ACTIVITY_INFO
import com.wn.common.dialog.ChoosePhotoDialog
import com.wn.common.dialog.ChooseSexDialog
import com.wn.common.dialog.SelectBirthdayDialog
import com.wn.common.provider.LoginServiceProvider
import com.wn.common.provider.UserServiceProvider
import com.wn.common.utils.FileManager
import com.wn.framework.base.BaseActivity
import com.wn.framework.ext.onClick
import com.wn.framework.glide.loadFile
import com.wn.framework.utils.ViewUtils.setClipViewCornerRadius
import com.wn.mod_login.R
import com.wn.mod_login.databinding.ActivityUserInfoBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 * @Author: wn
 * @Date: 2025/7/23 16:29
 * @Description: 用户信息 设置页
 */
@Route(path = USER_ACTIVITY_INFO)
class UserInfoActivity : BaseActivity<ActivityUserInfoBinding>() {

  override fun getLayoutRes() = R.layout.activity_user_info

  // 相机拍照 URI
  private var photoUri: Uri? = null

  // 裁剪图片 URI
  private var mUploadImageUri: Uri? = null

  // 裁剪图片文件
  private var mUploadImageFile: File? = null

  // 保存的头像路径
  private var saveAvatarPath: String? = null

  // 拍照回调
  private var mActivityResultLauncherTake: ActivityResultLauncher<Intent>? = null

  // 裁剪回调
  private var mActivityResultLauncherCrop: ActivityResultLauncher<Intent>? = null

  // 相册回调
  private var mActivityResultLauncherAlbum: ActivityResultLauncher<Intent>? = null
  override fun initView() {
    // 保存按钮设置圆角
    setClipViewCornerRadius(mBinding.tvSave, ConvertUtils.dp2px(20.0F))
    initUserInfo()
    initListener()
    registerActivityResult()
  }

  /**
   * 初始化用户信息
   */
  private fun initUserInfo() {
    val user = UserServiceProvider.getUserInfo()
    mBinding.user = user
  }

  /**
   * 初始化监听
   */
  private fun initListener() {
    mBinding.apply {
      // 头像栏
      clHead.onClick {
        showChoosePhotoDialog()
      }
      // 性别栏
      clSex.onClick {
        showSelectSexDialog()
      }
      // 生日栏
      clBirthday.onClick {
        showBirthdayDialog()
      }
      // 保存按钮
      tvSave.onClick {
        saveUserInfo()
      }
    }
  }

  /**
   * 注册 拍照 ，裁剪， 相册 的 回调，
   * 启动相应的功能后 ,没有问题 -- RESULT_OK ，在这里处理 数据，
   * 相册 在这里 获取数据，
   */
  private fun registerActivityResult() {
    // 拍照回调
    mActivityResultLauncherTake =
      registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
          workCropFun(photoUri)
        }
      }
    // 裁剪回调 -- 由 拍照触发
    mActivityResultLauncherCrop =
      registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
          setAvatar()
        }
      }
    // 相册回调
    mActivityResultLauncherAlbum =
      registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
          result.data?.data?.let {
            mUploadImageUri = it
            setAvatar()
          }
        }
      }
  }

  /**
   * 选择图片弹框
   */
  @SuppressLint("CheckResult")
  private fun showChoosePhotoDialog() {
    RxPermissions(this).request(
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
      Manifest.permission.READ_EXTERNAL_STORAGE,
      Manifest.permission.CAMERA
    ).subscribe {
      if (it)
        ChoosePhotoDialog.Builder(this)
          .setTakePicturesCall { takePictures() }
          .setPhotoAlbumCall { openAlbum() }
          .show()
      else
        ToastUtils.showLong(com.wn.framework.R.string.default_agree_permission)
    }
  }

  /**
   * 调取本地相机拍照
   */
  private fun takePictures() {
    val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    val values = ContentValues()
    //根据uri查询图片地址
    photoUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    LogUtils.i("photoUri:" + photoUri?.authority + ",photoUri:" + photoUri?.path)
    //放入拍照后的地址
    takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
    //调起拍照
    mActivityResultLauncherTake?.launch(takeIntent)
  }

  /**
   * 打开本地相册
   */
  private fun openAlbum() {
    val intentAlbum = Intent(Intent.ACTION_PICK, null)
    intentAlbum.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
    mActivityResultLauncherAlbum?.launch(intentAlbum)
  }

  /**
   * 系统裁剪方法
   */
  private fun workCropFun(imgPathUri: Uri?) {
    mUploadImageUri = null
    mUploadImageFile = null
    imgPathUri?.let {
      val imageObject: Any? = FileManager.getHeadJpgFile()
      if (imageObject is Uri) {
        mUploadImageUri = imageObject
      }
      if (imageObject is File) {
        mUploadImageFile = imageObject
      }
      val intent = Intent("com.android.camera.action.CROP")
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
      }
      intent.run {
        setDataAndType(it, "image/*") // 图片资源
        putExtra("crop", "true") // 裁剪
        putExtra("aspectX", 1) // 宽度比
        putExtra("aspectY", 1) // 高度比
        putExtra("outputX", 200) // 裁剪框宽度
        putExtra("outputY", 200) // 裁剪框高度
        putExtra("scale", true) // 缩放
        putExtra("return-data", false) // true-返回缩略图-data，false-不返回-需要通过 Uri
        putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()) // 保存的图片格式
        putExtra("noFaceDetection", true) // 取消人脸识别
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
          putExtra(MediaStore.EXTRA_OUTPUT, mUploadImageUri)
        } else {
          val imgCropUri = Uri.fromFile(mUploadImageFile)
          putExtra(MediaStore.EXTRA_OUTPUT, imgCropUri)
        }
      }
      mActivityResultLauncherCrop?.launch(intent)
    }
  }

  /**
   * 设置用户头像
   */
  private fun setAvatar() {
    val file: File? = if (mUploadImageUri != null) {
      FileManager.getMediaUri2File(mUploadImageUri!!)
    } else {
      mUploadImageFile
    }
    saveAvatarPath = file?.absolutePath

    mBinding.ivHead.loadFile(file)
  }

  /**
   * 选择 性别 弹框
   */
  private fun showSelectSexDialog() {
    ChooseSexDialog.Builder(this).setOnSexChooseCall {
      mBinding.tvSex.text = it
    }.show()
  }

  /**
   * 选择 生日日期 弹框
   */
  private fun showBirthdayDialog() {
    SelectBirthdayDialog.Builder(this).setBirthDayDateCall {
      mBinding.tvBirthday.text = it
    }.show()
  }

  /**
   * 保存用户信息
   */
  private fun saveUserInfo() {
    val user = UserServiceProvider.getUserInfo()
    user?.apply {
      icon = saveAvatarPath ?: ""
      nickname = mBinding.etName.text.toString().trim()
      sex = mBinding.tvSex.text.toString().trim()
      birthday = mBinding.tvBirthday.text.toString().trim()
      signature = mBinding.etSignature.text.toString().trim()
      // 采用 协程 做个延时操作
      lifecycleScope.launch {
        showLoading()
        UserServiceProvider.saveUserInfo(this@apply)
        delay(500)
        dismissLoading()
        ToastUtils.showShort(com.wn.framework.R.string.default_save_success)
      }
    } ?: kotlin.run {
      LoginServiceProvider.toLogin(this)
    }
  }

  companion object {
    /**
     * 跳转到用户信息设置页面
     */
    fun start(context: Context) {
      val intent = Intent(context, UserInfoActivity::class.java)
      context.startActivity(intent)
    }
  }
}